import React, { Component } from "react";
import "./index.scss";
import Button from "../../../component/button/index";
import { connect } from "react-redux";
import { List, Toast, InputItem, SegmentedControl } from "antd-mobile";
import { createForm } from "rc-form";
import TelIcon from "../../../images/icon/tel.png";
import { setContactList } from "../../../Redux/Action/contactInfo/index";
import { openContactUI, getContacts } from "../../../tools/native/navigate.js";
import { calData, hasRunLoop } from "./cal";

const submitPhone = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => {
	const str = submitPhone(value);
	return /^1[3456789]\d{9}$/.test(str);
};
const emojiReg = /(\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff])/g;
@connect(
	state => ({
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		contactInfo: state.contactInfoReducer.contactInfo
	}),
	dispatch => ({
		addContact: value => dispatch(setContactList(value))
	})
)
class XhfEditContactInfo extends Component {
	constructor(props) {
		super(props);
		this.state = {
			editable: true, //输入框是否可以输入
			urgentRelationShip: "02", //紧急联系人关系
			urgentRelationShipSecond: "01", //紧急联系人关系二
			urgentName: "", //紧急联系人姓名
			urgentPhone: "", //紧急联系人手机号
			urgentNameSecond: "", //紧急联系人姓名二
			urgentPhoneSecond: "", //紧急联系人手机号二
			relation1: [
				{
					label: "父母",
					value: "02",
					index: 0
				},
				{
					label: "配偶",
					value: "01",
					index: 1
				},
				{
					label: "子女",
					value: "00",
					index: 2
				}
			],
			relation2: [
				{
					label: "亲属",
					value: "03",
					index: 0
				},
				{
					label: "朋友",
					value: "04",
					index: 1
				},
				{
					label: "同事",
					value: "05",
					index: 2
				}
			],
			relationObj1: ["父母", "配偶", "子女"],
			relationObj2: ["亲属", "朋友", "同事"],
			selectedIndex1: 0,
			selectedIndex2: 0,
			contactCnt: 0,
			contactRelativeCnt: 0,
			contactCollectionCnt: 0,
			contactLoaninfoCnt: 0,
			contactCounterfeitCnt: 0,
			spaceID: "" // 随记生成一个计数
		};
	}
	componentWillReceiveProps = nextProps => {
		//props 更新
		if (nextProps.data.urgentName != this.props.data.urgentName) {
			const {
				urgentName,
				urgentNameSecond,
				urgentPhone,
				urgentPhoneSecond,
				relationObj1,
				relationObj2,
				selectedIndex1,
				selectedIndex2
			} = nextProps.data;
			this.setState({
				urgentName,
				urgentNameSecond,
				urgentPhone,
				urgentPhoneSecond,
				relationObj1,
				relationObj2,
				selectedIndex1,
				selectedIndex2
			});
		}
	};
	componentDidMount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom
		});
	}
	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
	}
	keyboardEvent = obj => {
		const id = document.activeElement.getAttribute("id");
		if (id !== "fix-cursor") {
			let winHeight = document.documentElement.clientHeight;
			document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
				winHeight * obj.heightper + "px";
		}
		if (id === "js-fix-bug") {
			document.activeElement.scrollIntoView();
		}
	};
	formatIndex = value => (value >= 0 ? value : 0); //确保不会因为等于-1而造成 can not read .. of undefined
	//文本框改变事件回调
	changeCallback(type, key, value) {
		(key === "urgentName" || key === "urgentNameSecond") &&
			(value = value.replace(emojiReg, ""));
		this.setState({
			[key]: type === "picker" ? value[0] : value
		});
	}

	relationChange = (value, type, key) => {
		const filterItem = this.state[key].filter(item => item.label === value)[0];
		this.setState({
			[type]: filterItem.index
		});
	};
	checkInfo() {
		const {
			urgentName,
			urgentNameSecond,
			urgentPhone,
			urgentPhoneSecond,
			urgentRelationShip,
			urgentRelationShipSecond
		} = this.state;
		if (!urgentRelationShip || !urgentRelationShipSecond) {
			Toast.info("请选择联系人关系", 2);
			return false;
		}
		if (!urgentName || !urgentNameSecond) {
			Toast.info("请填写姓名", 2);
			return false;
		}
		if (!urgentPhone || !urgentPhoneSecond) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(urgentPhone) || !checkPhoneReg(urgentPhoneSecond)) {
			Toast.info("请输入正确的手机号", 2);
			return false;
		}
		return true;
	}
	// 点击提交按钮
	next = () => {
		const {
			urgentName: contactName,
			urgentNameSecond: contactName2,
			urgentPhone: contactPhone,
			urgentPhoneSecond: contactPhone2,
			selectedIndex1,
			selectedIndex2,
			relation1,
			relation2,
			contactCnt,
			contactRelativeCnt,
			contactCollectionCnt,
			contactLoaninfoCnt,
			contactCounterfeitCnt
		} = this.state;
		const data = {
			contactName,
			contactName2,
			contactPhone,
			contactPhone2,
			selectedIndex1,
			selectedIndex2,
			relation1,
			relation2,
			contactCnt,
			contactRelativeCnt,
			contactCollectionCnt,
			contactLoaninfoCnt,
			contactCounterfeitCnt
		};
		this.checkInfo() && this.props.Submit(data);
	};
	openContact = type => {
		getContacts().then(res => {
			if (res.status === "1000") {
				openContactUI().then(res => {
					if (res.status === "1000") {
						const data = res.data;
						const name = data.name;
						const phone = data.phone[0];
						this.setState({
							["urgentName" + type]: name,
							["urgentPhone" + type]: phone
						});
					}
				});
				if (!hasRunLoop) {
					const data = calData(res.data);
					const {
						contactRelativeCnt,
						contactCollectionCnt,
						contactLoaninfoCnt,
						contactCounterfeitCnt
					} = data;
					this.setState({
						contactCnt: res.data.length || -1,
						contactRelativeCnt: contactRelativeCnt || -1,
						contactCollectionCnt: contactCollectionCnt || -1,
						contactLoaninfoCnt: contactLoaninfoCnt || -1,
						contactCounterfeitCnt: contactCounterfeitCnt || -1
					});
				}
			}
		});
	};
	render() {
		const {
			urgentName,
			urgentNameSecond,
			urgentPhone,
			urgentPhoneSecond,
			relationObj1,
			relationObj2,
			selectedIndex1,
			selectedIndex2
		} = this.state;
		return (
			<div>
				<div className="edit-contact-info-container">
					<div className="info-title">常用联系人1</div>
					<InputItem
						extra={
							<SegmentedControl
								selectedIndex={selectedIndex1}
								values={relationObj1}
								onValueChange={e =>
									this.relationChange(e, "selectedIndex1", "relation1")
								}
							/>
						}
					>
						联系人关系
					</InputItem>
					<List className="person-info-list">
						<InputItem
							id="fix-cursor"
							className="my-input my-input-name"
							type="text"
							name="input"
							placeholder="请填写真实姓名"
							value={urgentName}
							clear
							onChange={this.changeCallback.bind(this, "input", "urgentName")}
						>
							姓名
							<img
								alt="guide"
								className="icon-help"
								src={TelIcon}
								onClick={() => this.openContact("")}
							/>
						</InputItem>

						<InputItem
							className="my-input my-input-0"
							name="input"
							type="phone"
							placeholder="请输入联系人手机号"
							clear
							value={urgentPhone}
							onChange={this.changeCallback.bind(this, "input", "urgentPhone")}
						>
							手机号
						</InputItem>
					</List>
					<div className="info-title">常用联系人2</div>
					<InputItem
						extra={
							<SegmentedControl
								selectedIndex={selectedIndex2}
								values={relationObj2}
								onValueChange={e =>
									this.relationChange(e, "selectedIndex2", "relation2")
								}
							/>
						}
					>
						联系人关系
					</InputItem>
					<List className="person-info-list">
						<InputItem
							placeholder="请填写真实姓名"
							clear
							className="my-input my-input-name"
							type="text"
							value={urgentNameSecond}
							onChange={this.changeCallback.bind(
								this,
								"input",
								"urgentNameSecond"
							)}
						>
							姓名
							<img
								alt="guide"
								className="icon-help"
								src={TelIcon}
								onClick={() => this.openContact("Second")}
							/>
						</InputItem>

						<InputItem
							id="js-fix-bug"
							className="my-input my-input-0"
							type="phone"
							clear
							placeholder="请输入联系人手机号"
							value={urgentPhoneSecond}
							onChange={this.changeCallback.bind(
								this,
								"input",
								"urgentPhoneSecond"
							)}
						>
							手机号
						</InputItem>
					</List>
				</div>
				<div id="js-btn">
					<Button
						style={{
							marginTop: "40px"
						}}
						onClick={this.next}
					>
						确认
					</Button>
				</div>
				<div id={"keybordb_" + this.state.spaceID}></div>
			</div>
		);
	}
}

export default createForm()(XhfEditContactInfo);
